package com.cyh.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class ServerSocketChannelDemo {
    public static void main(String[] args) throws IOException, InterruptedException {
        int port = 8080;
        ByteBuffer buffer = ByteBuffer.wrap("hello cyh".getBytes());
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.socket().bind(new InetSocketAddress(port));
        //设置非阻塞模式
        ssc.configureBlocking(false);
        while (true) {
            System.out.println("Wait for connections");
            SocketChannel sc = ssc.accept();
            if(sc == null) {
                System.out.println("null");
                Thread.sleep(2000);
            }else {
                System.out.println("Incoming connection from: " + sc.socket().getRemoteSocketAddress());
                buffer.rewind();

                sc.write(buffer);
                sc.close();
            }
        }

        //浏览器输入：127.0.0.1:8080   看打印
    }
}
